﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vowei.Data.Models;
using Vowei.Data.Helpers;
using Vowei.Core.Models;
using Vowei.Data;
using Vowei.Core;
using Newtonsoft.Json;
using Vowei.Web.Security;
using Vowei.Web.Models;
using Vowei.Web.Helpers;
using System.Text;

namespace Vowei.Web.Controllers
{
    public class MilestoneController : G18nController
    {
        private IVoweiContext _context;
        private IUser _user;
        public MilestoneController(IVoweiContext context, IUser user)
        {
            _context = context;
            _user = user;
        }

        //
        // GET: /Milestone/
        [PermissionAuthorize(RequiredPermission = Constants.Permission.Read.Milestone)]
        public ActionResult Index()
        {
            // TODO: 将这个变成一个通用的函数
            var list = _context.Milestones.Query.Active().ToArray();
            return ViewList(list);
        }

        [PermissionAuthorize(RequiredPermission = Constants.Permission.Read.Milestone)]
        public ActionResult UnAssigned()
        {
            // TODO: 将这个变成一个通用的函数
            var list = _context.UnAssignedMilestone().ToArray();
            return ViewList(list);
        }

        [PermissionAuthorize(RequiredPermission = Constants.Permission.Write.Milestone)]
        public ActionResult Create()
        {
            return Edit((Guid?)null);
        }

        [HttpPost]
        [PermissionAuthorize(RequiredPermission = Constants.Permission.Write.Milestone)]
        public ActionResult Create(Milestone item)
        {
            item.OpenDate = DateTime.Now;
            item.Reporter = ViewHelpers.GetLogonUserName();
            var result = Edit(item);
            if (Request.AcceptTypes.Any(s => s == "application/json"))
            {
                var json = ViewHelpers.SerializeToJson(item, new List<JsonConverter>());
                Response.Write(json);

                return WebConstants.HttpSuccess;
            }
            else
                return result;
        }

        [PermissionAuthorize(RequiredPermission = Constants.Permission.Read.Milestone)]
        public ActionResult Details(Guid id)
        {
            var milestone = _context.Milestones.Include("BelongsToMilestone").Include("Comments").Include("Children").Query.First(m => m.ID == id);
            return View("Details", milestone).AddJsonSupport();
        }

        public ActionResult Close(Guid id)
        {
            var milestone = _context.Milestones.Find(id);
            if (milestone == null)
                throw new InvalidOperationException(string.Format(T("找不到id为[{0}]的项目或者里程碑！"), id));

            var activeTickets = milestone.AllTickets(_context).Active();
            if (activeTickets.Count() > 0)
            {
                var ticketList = new StringBuilder();
                foreach (var ticket in activeTickets)
                {
                    ticketList.Append("<ul>");
                    ticketList.Append(string.Format(
                        "<li><a href=\"/Tickets/Details/{0}\">{1}</a></li>", ticket.ID, ticket.Title));
                    ticketList.Append("</ul>");
                }

                throw new InvalidOperationException(string.Format(T("在关闭里程碑/项目 [{0}] 之前，需要将下列任务或者需求关闭</br>{1}"), milestone.Title, ticketList.ToString()));
            }

            // 还没有完全完成！
            throw new NotImplementedException();

            //  return RedirectToAction("Details", new { id = id });
        }

        [PermissionAuthorize(RequiredPermission = Constants.Permission.Write.Milestone)]
        public ActionResult Edit(Guid? id)
        {
            return View("Edit", EntityHelpers.GenericGetObjectDetails<Milestone>(id, _context)).AddJsonSupport();
        }

        // TODO: 这个类的大部分函数都可以和ProjectController里面的工作合并！
        [HttpPost]
        [PermissionAuthorize(RequiredPermission = Constants.Permission.Write.Milestone)]
        public ActionResult Edit(Milestone milestone)
        {
            EditingHelpers.GenericEndEdit(milestone, _context, _user);

            if (Request != null &&
                Request.AcceptTypes.Any(s => s == "application/json"))
            {
                return WebConstants.HttpSuccess;
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        [PermissionAuthorize(RequiredPermission = Constants.Permission.Read.Milestone)]
        public ActionResult Tickets(Guid id)
        {
            return ViewTickets(LoadTicketsFor(_context, id));
        }

        [PermissionAuthorize(RequiredPermission = Constants.Permission.Read.Milestone)]
        public ActionResult ClosedTickets(Guid id)
        {
            ViewBag.Title = T("已关闭的任务");
            return ViewTickets(LoadTicketsFor(_context, id).Closed());
        }

        [PermissionAuthorize(RequiredPermission = Constants.Permission.Read.Milestone)]
        public ActionResult ActiveTickets(Guid id)
        {
            ViewBag.Title = T("未关闭的任务");
            return ViewTickets(LoadTicketsFor(_context, id).Active());
        }

        private ActionResult ViewTickets(IQueryable<Ticket> query)
        {
            var list = query.ToArray();

            return View("Tickets", list).AddJsonSupport();
        }

        private IQueryable<Ticket> LoadTicketsFor(IVoweiContext context, Guid milestoneId)
        {
            var milestone = context.Milestones.Find(milestoneId);

            ViewData["Milestone"] = milestone;

            return milestone.AllTickets(context).OfType<Ticket>();
        }

        private ActionResult ViewList(Milestone[] list)
        {
            if (Request.AcceptTypes.Any(s => s == "application/json"))
            {
                var json = ViewHelpers.SerializeToJson(list, new List<JsonConverter>());
                Response.Write(json);

                return WebConstants.HttpSuccess;
            }
            else
                return View("Index", list).AddJsonSupport();
        }
    }
}
